<template>
  <div class="params">
      <!-- 导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 视图 -->
    <el-card >
      <!-- 警告区域 -->
        <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" :closable='false' show-icon></el-alert>
        <!-- 选择分类 -->
        <el-row class="cateparams">
          <el-col>
            <span>选择商品分类：</span>
            <!-- 级联选择框 -->
             <el-cascader :options="catelist" :props="cateProps" v-model="selectedCateKeys" @change="handleChange" clearable  >
          </el-cascader>
          </el-col>
        </el-row>
        <!-- 页签区 -->
         <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="动态参数" name="many">
              <el-button type='primary' size='mini' :disabled='isbtndisabled' @click="adddialogVisible=true">添加参数</el-button>
              <!-- table -->
              <el-table :data='manytable' border stripe>
                <!-- 展开行 -->
                <el-table-column type='expand'>
                  <template slot-scope="scope">
                    <el-tag v-for="(item,index) in scope.row.attr_vals" :key='index' closable @close='handleClose(index,scope.row)'>
                      {{item}}
                    </el-tag>
                    <!--输入文本框 -->
                    <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                     </el-input>
                     <!-- 添加按钮-->
                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                  </template>
                </el-table-column>
                <!-- 索引 -->
                <el-table-column type='index'></el-table-column>
                <el-table-column label='参数' prop='attr_name'></el-table-column>
                 <el-table-column label='操作' >
                   <template slot-scope="scope">
                     <el-button type="primary" icon="el-icon-edit" size='mini' @click="showeditdialog(scope.row.attr_id)">编辑</el-button>
                     <el-button type="danger" icon="el-icon-delete" size='mini' @click="deleteditdialog(scope.row.attr_id)">删除</el-button>
                   </template>
                 </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="静态属性" name="only">
               <el-button type='primary' size='mini' :disabled='isbtndisabled' @click="adddialogVisible=true">添加属性</el-button>
                <!-- table -->
              <el-table :data='onlytable' border stripe>
                <!-- 展开行 -->
                <el-table-column type='expand'>
                   <template slot-scope="scope">
                    <el-tag v-for="(item,index) in scope.row.attr_vals" :key='index' closable @close='handleClose(index,scope.row)'>
                      {{item}}
                    </el-tag>
                    <!-- 文本输入框 -->
                    <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                     </el-input>
                     <!-- 添加按钮-->
                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                  </template>
                    
                </el-table-column>
                <!-- 索引 -->
                <el-table-column type='index'></el-table-column>
                <el-table-column label='属性名称' prop='attr_name'></el-table-column>
                 <el-table-column label='操作' >
                   <template slot-scope="scope">
                     <el-button type="primary" icon="el-icon-edit" size='mini' @click="showeditdialog(scope.row.attr_id)">编辑</el-button>
                     <el-button type="danger" icon="el-icon-delete" size='mini' @click="deleteditdialog(scope.row.attr_id)">删除</el-button>
                   </template>
                 </el-table-column>
              </el-table>
            </el-tab-pane>
        </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog :title="'添加'+titletext" :visible.sync="adddialogVisible" width="50%" @close='closedialog'> 
      <!-- biaodan -->
        <el-form :model="addparamsrulesForm" :rules="addparamsrules" ref="addparamsRef" label-width="100px">
         <el-form-item :label="titletext" prop="attr_name">
         <el-input v-model="addparamsrulesForm.attr_name"></el-input>
         </el-form-item>
         </el-form>
        <span slot="footer" class="dialog-footer">
       <el-button @click="adddialogVisible= false">取 消</el-button>
       <el-button type="primary" @click="addParamsSubmit">确 定</el-button>
         </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog title="修改参数" :visible.sync="editdialogVisible" width="50%" @close='closeeditdialog'> 
      <!-- biaodan -->
        <el-form :model="editparamsrulesForm" :rules="editparamsrules" ref="editparamsRef" label-width="100px">
         <el-form-item label="参数" prop="attr_name">
         <el-input v-model="editparamsrulesForm.attr_name"></el-input>
         </el-form-item>
         </el-form>
        <span slot="footer" class="dialog-footer">
       <el-button @click="editdialogVisible= false">取 消</el-button>
       <el-button type="primary" @click="editparams">确 定</el-button>
         </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
data(){
  return{
       catelist:[],
       cateProps:{
         value:'cat_id',
         label: 'cat_name',
         children:'children',
         expandTrigger: 'hover',
         checkStrictly:true
       },//级联选择框的配置对象
       selectedCateKeys:[],
       activeName:'many',//被激活的页签名
       manytable:[],//动态参数
       onlytable:[],//静态属性
       adddialogVisible:false,//控制对话框的显示隐藏
       addparamsrulesForm:{
         attr_name:''
       },//添加参数的表单数据
       addparamsrules:{
         attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }],
       },//规则
       editdialogVisible:false,//修改对话框
       editparamsrulesForm:{
         
       },//修改参数的表单数据
       editparamsrules:{
         attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
       },
       inputVisible:false,//默认情况下隐藏文本框
       inputValue:'',
  }
},
created(){
 this.getcatelist()//获取所有的分类列表
},
computed:{
  //如果按钮需要被禁用 返回true
 isbtndisabled(){
    if(this.selectedCateKeys.length !== 3) return true
    return false
 },
 //选中的三级菜单id
 cate_id(){
   if(this.selectedCateKeys.length == 3) return this.selectedCateKeys[2]
   return null
 },
 //动态还是静态
 titletext(){
   if(this.activeName == 'many') {return '动态参数'}
   else{
      return '静态属性'
   }
  
 }
},
methods:{

  async  getcatelist(){
     let {data:res} = await this.$http.get('categories')
     if (res.meta.status !== 200) return this.$message.error('获取分类失败')
       this.catelist = res.data
      // console.log(res.data)  
    },
    /* 级联选中项触发 */
    handleChange(){
        //console.log(this.selectedCateKeys)
        this.getparamsdata()
      
      },
      //获取参数
     async getparamsdata(){
        if (this.selectedCateKeys.length !== 3) {
          //如果选中的不是三级分类
          this.selectedCateKeys = []
          this.manytable = []
          this.onlytable = []
          return
        }
            /* 控制级联选择器的选择 */
            
        //根据选中的id和当前面板 获取参数属性   
        let{data:res}  = await   this.$http.get(`categories/${this.cate_id}/attributes`,{
          params:{sel:this.activeName}
        }) 
       if(res.meta.status !== 200) this.$message.error('获取参数失败')
       //console.log(res.data)
       //判断数据是那个table
       res.data.forEach(element => {
         element.attr_vals = element.attr_vals ? element.attr_vals.split(' '):[]
         element.inputVisible = false
         element.inputValue = ''
       });
       /* 添加boolean控制文本框的显示隐藏和自己的数据 */
       if (this.activeName == 'many') {
         this.manytable = res.data
       }else{
         this.onlytable = res.data
       }
      },
      /* 点击页签的事件 */
      handleClick(){
       // console.log(this.activeName)
         this.getparamsdata()
      },
      /*关闭对话框重置表单 */
      closedialog(){
        this.$refs.addparamsRef.resetFields()
      },
      /* 点击添加参数  */
      addParamsSubmit(){
       this.$refs.addparamsRef.validate(async valid => {
         if (!valid) return
         let{data:res} = await this.$http.post(`categories/${this.cate_id}/attributes`,{
           attr_name:this.addparamsrulesForm.attr_name,
           attr_sel: this.activeName
         })
         if (res.meta.status !== 201) this.$message.error('添加参数失败')
         this.$message.success('添加参数成功')
         this.adddialogVisible = false
         this.getparamsdata()
       })
      },
    //修改对话框
     async showeditdialog(id){
        this.editdialogVisible = true
        let {data:res} = await this.$http.get(`categories/${this.cate_id}/attributes/${id}`,{params:{attr_sel:this.activeName}})
        if (res.meta.status !== 200 ) this.$message.error('获取添加参数失败')
        this.editparamsrulesForm = res.data
       // console.log(res.data)
        
      },
      /* 重置修改表单 */
      closeeditdialog(){
        this.$refs.editparamsRef.resetFields()
      },
      editparams(){
        this.$refs.editparamsRef.validate(async valid => {
         if (!valid) return
         let{data:res} = await this.$http.put(`categories/${this.cate_id}/attributes/${this.editparamsrulesForm.attr_id}`,{
           attr_name:this.editparamsrulesForm.attr_name,
           attr_sel: this.activeName
         })
         if (res.meta.status !== 200) this.$message.error('修改参数失败')
         this.$message.success('修改参数成功')
         this.getparamsdata()
         this.editdialogVisible = false
       }) 
      },
      //根据id删除参数
    async   deleteditdialog(id){
     let confirm =await   this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
     if (confirm !== 'confirm') {//取消
       return this.$message.info('取消删除')
     }
        let {data:res} = await this.$http.delete(`categories/${this.cate_id}/attributes/${id}`)
        if (res.meta.status !==200)return this.$message.error('删除参数失败')
            
         this.$message.success('删除参数成功')
         this.getparamsdata()

      },
      /* 文本框失去焦点   */
   async  handleInputConfirm(row){
       if (row.inputValue.trim().length===0) {
         row.inputValue = ''
         row.inputVisible = false
         return
       }
       //没有return 输入内容添加tag，
       row.attr_vals.push(row.inputValue.trim())
       row.inputValue = ''
       row.inputVisible = false
       //保存到数据库
          this.saveattr_vals(row)
     },
    async saveattr_vals(row){
        let {data:res} =await this.$http.put(`categories/${this.cate_id}/attributes/
       ${row.attr_id}`,{attr_name:row.attr_name,attr_sel:row.attr_sel,attr_vals:row.attr_vals.join(' ')})
       if (res.meta.status !== 200) return this.$message.error('修改参数项失败')
         this.$message.success('修改参数项成功')

     },
     /* 点击按钮。展示 */
     showInput(row){
      row.inputVisible = true
      //自动得到焦点
      this.$nextTick(_ => {//$nextTick作用：当页面上元素被重新渲染之后才会指定回调函数
          this.$refs.saveTagInput.$refs.input.focus();
        });
     },
     /* 删除对应的参数可选项 */
     handleClose(index,row){
       row.attr_vals.splice(index,1)
       this.saveattr_vals(row)
     }

},
}
</script>

<style lang="less" scoped>
.cateparams{
  margin: 15px 0;
  color: rgb(220, 207, 231);
}
.el-tag{
  margin: 10px;
}
.input-new-tag{
  width: 100px;
}
</style>